﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using Barry.BarbeSystem.Business;
using Barry.BarbeSystem.Filters;
using Barry.BarbeSystem.Models;

namespace Barry.BarbeSystem.Controllers
{
    [CustomerAuthorizationFilter]
    public class MemberController : Controller
    {
        private IRepository<Member> repository;
        private IRepository<Discount> discount;
        private IRepository<BarberCategory> _categoryRepository;
        private IRepository<ConsumeHistory> historyRepository;



        private MemberRepository memberRepository;

        public MemberController()
        {
            this.memberRepository = new MemberRepository();
            repository = new Repository<Member>();
            discount = new Repository<Discount>();
            historyRepository = new Repository<ConsumeHistory>();
            _categoryRepository = new Repository<BarberCategory>();
        }



        public ActionResult Index()
        {
            return View();
        }


        public ActionResult CheckOut(int id)
        {
            var categories = _categoryRepository.GetAll().Where(i => i.Enable == true);
            var result = categories.Select(c => new SelectListItem()
            {
                Text = c.Name,
                Value = c.Id.ToString()
            }).ToList();
            result.Insert(0, new SelectListItem() { Text = "请选择", Value = "-1" });
            ViewData["category"] = result;
            Member membermodel = repository.Get(id);
            return View(membermodel);
        }

        [HttpPost]
        public JsonResult ConsumeInfo(int peopleId, decimal consumeMoney, string details)
        {
            bool check = true;
            try
            {
                var currentUser = memberRepository.Get(peopleId);
                ConsumeHistory history = new ConsumeHistory()
                    {
                        ConsumeAmount = -consumeMoney,
                        CurrentDate = DateTime.Now,
                        Balance = currentUser.Balance - consumeMoney,
                        ConsumeDetail = details,
                        Member = currentUser,
                        Remarks = "消费"
                    };

                memberRepository.Consume(currentUser, history);

            }
            catch (Exception e)
            {
                check = false;
                //TODO
            }

            JsonResult json = new JsonResult();
            json.Data = new { success = check };
            return json;
        }

        [HttpPost]
        public ActionResult CheckOut(int id, ConsumeHistory history)
        {
            return View();
        }



        public JsonResult PageIndex(MemberPageRequest request)
        {
            //return View();
            int itemCounts;
            var results = memberRepository.Get(request, out itemCounts);

            JsonResult jes = new JsonResult();
            jes.Data = new GridResponseInfo() { rows = results, total = itemCounts };
            return jes;
        }


        public FileResult DownLoad()
        {
            var stream = new MemoryStream();

            var streamWriter = new StreamWriter(stream, Encoding.UTF8);

            var result = memberRepository.GetAllMember();
          
            if (result != null && result.Count > 0)
            {

                foreach (var member in result)
                {
                    streamWriter.WriteLine(member.ToString());
                }
            }
            streamWriter.Flush();
            stream.Seek(0, SeekOrigin.Begin);
            return new FileStreamResult(stream, "text/plain")
                {
                    FileDownloadName = DateTime.Now+"数据备份.txt"
                };
        }

        public ActionResult Consume()
        {
            return View();
        }

        //
        // GET: /Member/Details/5

        public ActionResult Details(int id = 0)
        {
            Member membermodel = repository.Get(id);
            if (membermodel == null)
            {
                return HttpNotFound();
            }
            return View(membermodel);
        }

        //
        // GET: /Member/Create

        public ActionResult Create()
        {
            InitDiscount();


            return View();
        }

        private void InitDiscount()
        {
            var result = discount.GetAll().OrderBy(o => o.DiscountInfo).ToList();
            ViewData["discount"] = result.Select(c => new SelectListItem()
                {
                    Text = c.DiscountInfo.ToString(),
                    Value = c.DiscountInfo.ToString()
                });
        }

        //
        // POST: /Member/Create

        [HttpPost]
        public ActionResult Create(Member membermodel)
        {
            if (ModelState.IsValid)
            {
                membermodel.Enable = true;
                IRepository<Member> repository = new Repository<Member>();
                repository.Save(membermodel);

                ConsumeHistory history = new ConsumeHistory()
                    {
                        Member = membermodel,
                        Balance = membermodel.Balance,
                        ConsumeAmount = membermodel.Balance,
                        Remarks = "开卡",
                        CurrentDate = DateTime.Now
                    };
                historyRepository.Save(history);

                return RedirectToAction("Index");
            }
            InitDiscount();
            return View(membermodel);
        }

        //
        // GET: /Member/Edit/5

        public ActionResult ConsumeHistory()
        {
            return View();
        }

        public JsonResult PageConsumeHistory(MemberPageRequest request)
        {
            //return View();
            int itemCounts;
            var results = memberRepository.GetHistory(request, out itemCounts);

            JsonResult jes = new JsonResult();
            jes.Data = new GridResponseInfo() { rows = results, total = itemCounts };
            return jes;
        }

        public ActionResult Edit(int id = 0)
        {
            Member membermodel = repository.Get(id);
            if (membermodel == null)
            {
                return HttpNotFound();
            }

            InitDiscountSelect(membermodel);


            return View(membermodel);
        }

        private void InitDiscountSelect(Member membermodel)
        {
            var result = discount.GetAll().ToList().OrderBy(i => i.DiscountInfo);

            var selectList = result.Select(c => new SelectListItem()
                {
                    Text = c.DiscountInfo.ToString(),
                    Value = c.DiscountInfo.ToString()
                });
            var listInfo = selectList.ToList();
            listInfo.ForEach(delegate(SelectListItem item)
                {
                    if (item.Value == membermodel.Discount.ToString("F2"))
                    {
                        item.Selected = true;
                    }
                });

            ViewData["discount"] = listInfo;
        }

        //
        // POST: /Member/Edit/5

        [HttpPost]
        public ActionResult Edit(Member membermodel)
        {
            if (ModelState.IsValid)
            {
                repository.Update(membermodel);
                return RedirectToAction("Index");
            }
            return View(membermodel);
        }


        [HttpPost]
        public ActionResult Recharge(Member member)
        {
            if (ModelState.IsValid)
            {

                member.Balance += member.RechargeNumber;
                var currentMember = memberRepository.Get(member.Id);
                currentMember.Balance = member.Balance;
                currentMember.Discount = member.Discount;
                //   repository.Update(member);
                ConsumeHistory history = new ConsumeHistory()
                {
                    Balance = member.Balance,
                    ConsumeAmount = member.RechargeNumber,
                    Remarks = "充值",
                    CurrentDate = DateTime.Now
                };
                memberRepository.Recharge(currentMember, history);
                return RedirectToAction("Index");
            }


            return View(member);
        }



        public ActionResult Recharge(int id = 0)
        {
            Member membermodel = repository.Get(id);
            if (membermodel == null)
            {
                return HttpNotFound();
            }
            InitDiscountSelect(membermodel);

            return View(membermodel);
        }

        //
        // GET: /Member/Delete/5
        [HttpPost]
        public JsonResult Delete(int id = 0)
        {
            JsonResult j = new JsonResult();
            var obj = repository.Get(id);
            if (obj != null)
            {
                obj.Enable = false;
                repository.Update(obj);
                j.Data = new { success = true };

            }
            else
            {
                j.Data = new { success = false };
            }


            //Member membermodel = db.Courses.Find(id);
            //if (membermodel == null)
            //{
            //    return HttpNotFound();
            //}
            //return View(membermodel);
            return j;
        }



        protected override void Dispose(bool disposing)
        {
            //db.Dispose();
            //base.Dispose(disposing);
        }
    }
}